import { Modal, Form, Input, Select, Button, message } from 'antd'
import services from '@/services'
import type { InterceptRule } from '@/services/features/sensitive-intercepts'
import { InterceptRuleType } from '@/services/features/sensitive-intercepts'
import './Edit.module.less'

export default function EditModal(props: {
  editing: false | true | InterceptRule
  onFinish: () => void
}) {
  const { editing, onFinish } = props

  const title = editing !== false ? (editing === true ? '新建规则' : '编辑规则') : ''

  return <Modal
    title={title}
    footer={null}
    width="500px"
    open={editing !== false}
    onCancel={onFinish}
    destroyOnClose
  >
    {editing !== false ? <Content editing={editing} onFinish={onFinish} /> : null}
  </Modal>
}

function Content(props: { editing: true | InterceptRule; onFinish: () => void }) {
  const { editing, onFinish } = props

  const [form] = Form.useForm()

  const initialValues = useMemo(
    () =>
      editing === true ? { name: '', type: InterceptRuleType.Exact, keyword: '' } : { ...editing },
    [editing],
  )

  const keywordValidator = useCallback(
    async (_: unknown, value: InterceptRule['keyword']) => {
      const ruleType = form.getFieldValue('type') as InterceptRuleType
      if (!value)
        throw new Error(ruleType === InterceptRuleType.Regex ? '请输入正则表达式' : '请输入关键词')

      // 如果匹配类型是“正则匹配”，则检查输入的正则表达式是否合法
      if (ruleType === InterceptRuleType.Regex) {
        try {
          new RegExp(value)
        } catch {
          throw new Error('请输入正确的正则表达式')
        }
      }

      return Promise.resolve()
    },
    [form],
  )

  const [submitting, setSubmitting] = useState(false)
  const submit = useCallback(
    async (values: Pick<InterceptRule, 'name' | 'type' | 'keyword'>) => {
      setSubmitting(true)
      const res = await services.features.sensitiveIntercepts.addOrUpdate({
        id: editing === true ? undefined : editing.id,
        enable: editing === true ? true : editing.enable,
        ...values,
      })
      setSubmitting(false)
      if (res.success) {
        void message.success('保存成功')
        onFinish()
      } else {
        void message.warning(`保存失败：${res.error}`)
      }
    },
    [editing, onFinish],
  )

  return <Form
    styleName="edit"
    labelCol={{ span: 6 }}
    form={form}
    initialValues={initialValues}
    onFinish={submit}
  >
    <Form.Item rules={[{ required: true }]} label="规则名称" name="name">
      <Input />
    </Form.Item>

    <Form.Item label="匹配类型" name="type">
      <Select>
        <Select.Option value={InterceptRuleType.Exact}>关键词精确匹配</Select.Option>
        <Select.Option value={InterceptRuleType.Fuzzy}>关键词包含匹配</Select.Option>
        <Select.Option value={InterceptRuleType.Regex}>关键词正则匹配</Select.Option>
      </Select>
    </Form.Item>

    <Form.Item
      rules={[{ required: true, validator: keywordValidator }]}
      label="关键词或正则"
      name="keyword"
    >
      <Input />
    </Form.Item>

    <Form.Item wrapperCol={{ offset: 6 }}>
      <Button loading={submitting} type="primary" htmlType="submit">
        保存
      </Button>
    </Form.Item>
  </Form>
}
